package org.stragma.util

import org.kiama.rewriting._
import org.kiama.rewriting.Rewriter.{all,attempt,innermost,rulefs,Strategy,Term,topdown}

object ListManager {
	/*
	 * Method recurses and flattens nested loops (i.e. List(term1,List(term2,term3)) is converted to
	 * List(term1,term2,term3))
	 */
	def flattenTerm(terms : List[Term]) : List[Term] = {
		var result = List[Term]()
		terms foreach { item =>
			item match {
				case e : List[Term] =>
					result = result ::: flattenTerm(e)
				case e : Term =>
					result = result ::: List(e)
			}
		}
		return result
	}
	
	/*
	 * Performs a fold right. f is the preliminary strategy. s2 is the
	 * secondary strategy applied to the result of 'f'
	 */
	def foldr(s1:Term,s2:Strategy,f:Strategy) = rulefs {
		case Nil => s1
		case e : List[Term] =>
			// Append the initial term to the list
			val terms = (e).reverse
			var currentTerm = s1
			
			// As the list is reversed we are iterating in reverse which is the r in foldr
			terms foreach { item =>
				val preProcRes = f(item).get
				currentTerm = s2((currentTerm,preProcRes)).get
		}
			
			currentTerm
	}
}